package drds.plus.datanode.api;

import drds.plus.common.utils.TStringUtil;
import drds.plus.datanode.configuration.DataSourceIndexAndNeedRetryIfDailed;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DataNodeHintParser {

    public static DataSourceIndexAndNeedRetryIfDailed convertHint2Index(String sql) {
        String dataNodeIdHint = extractDataNodeIdHint(sql);
        if (null != dataNodeIdHint && !dataNodeIdHint.equals("")) {
            String[] hintWithRetry = dataNodeIdHint.split(",");
            if (hintWithRetry.length == 1) {
                String index = DataNodeHintParser.getIndexFromHintPiece(hintWithRetry[0]);
                return new DataSourceIndexAndNeedRetryIfDailed(index, false);
            } else if (hintWithRetry.length == 2) {
                String index = DataNodeHintParser.getIndexFromHintPiece(hintWithRetry[0]);
                boolean retry = DataNodeHintParser.getFailRetryFromHintPiece(hintWithRetry[1]);
                return new DataSourceIndexAndNeedRetryIfDailed(index, retry);
            } else {
                throw new IllegalArgumentException("the standard datanode hint is:'groupIndex:12[,needRetryIfDailed:true]'" + ",current hint is:" + dataNodeIdHint);
            }
        } else {
            return null;
        }
    }

    private static String getIndexFromHintPiece(String indexPiece) {
        String[] piece = indexPiece.split(":");
        if (piece[0].trim().equalsIgnoreCase("groupIndex")) {
            return piece[0];
        } else {
            throw new IllegalArgumentException("the standard datanode hint is:'groupIndex:12[,needRetryIfDailed:true]'" + ",current dataSourceIndex hint is:" + indexPiece);
        }
    }

    private static boolean getFailRetryFromHintPiece(String retryPiece) {
        String[] piece = retryPiece.split(":");
        if (piece[0].trim().equalsIgnoreCase("needRetryIfDailed")) {
            return Boolean.valueOf(piece[1]);
        } else {
            throw new IllegalArgumentException("the standard datanode hint is:'groupIndex:12[,needRetryIfDailed:true]'" + ",current executor hint is:" + retryPiece);
        }
    }

    public static String extractDataNodeIdHint(String sql) {
        return TStringUtil.getBetween(sql, "/*+data_node({", "})*/");
    }

    public static String removeDataNodeIdHint(String sql) {
        String tddlHint = extractDataNodeIdHint(sql);
        if (null == tddlHint || "".equals(tddlHint)) {
            return sql;
        }

        sql = TStringUtil.removeBetweenWithSplitor(sql, "/*+data_node({", "})*/");
        return sql;
    }

    public static String buildDataNodeIdHint(String dataNodeId) {
        return "/*+data_node({" + dataNodeId + "})*/";
    }

    public static void main(String[] args) {
        String sql = "/*+data_node({groupIndex:12})*/query * from tab";
        System.out.println(convertHint2Index(sql));
        System.out.println(removeDataNodeIdHint(sql));
    }
}
